#!/usr/bin/python2.5
# Copyright 2007 Alex K (wtwf.com) All rights reserved.

"""
Download the contents of a picasa web album

downloadpicasawebalbum picasaurl [destination_directory]
"""

__author__ = "Alex K (wtwf.com)"

try:
  from xml.etree import ElementTree # for Python 2.5 users
except:
  from elementtree import ElementTree

import os
import sys
import cgi
import getopt
import logging
import csv
import urllib
import re
import xml.sax.saxutils

def usage(code, msg=''):
  if code:
    fd = sys.stderr
  else:
    fd = sys.stdout
  PROGRAM = os.path.basename(sys.argv[0])
  print >> fd, __doc__ % locals()
  if msg:
    print >> fd, msg
  sys.exit(code)

def DownloadPicasaWebAlbum(url, destination):
  logging.info("Finding RSS feed url for '%s'", url)
  alt_re = re.compile(r'<[^>]*alternate[^>]*href="([^"]*)"')
  rss = None
  for line in urllib.urlopen(url):
    res = alt_re.search(line)
    if res:
      rss = xml.sax.saxutils.unescape(res.group(1))
      break
  if not rss:
    logging.fatal("Could not find feed url for album.")
  logging.info("Fetching RSS feed url '%s'", rss)
  rss_file = urllib.urlopen(rss)
  ProcessRssFeed(rss_file, destination)

def ProcessRssFeed(feed_file, destination):
  logging.info("processing RSS feed contents")
  tree = ElementTree.parse(feed_file)
  root = tree.getroot()
  channel = root.find('channel')
  items = channel.findall('item')
  for item in items:
    enc = item.find('enclosure')
    url = enc.get('url')
    filename = os.path.basename(urllib.unquote_plus(url))
    logging.info("Fetching: %s", filename)
    url_file = urllib.urlopen(url)
    file_out = open(os.path.join(destination, filename), "wb")
    file_out.write(url_file.read())
    file_out.close()
    url_file.close()

def main():
  logging.basicConfig()
  logging.getLogger().setLevel(logging.DEBUG)

  # parse command line options
  try:
    opts, args = getopt.getopt(sys.argv[1:], "", [])
  except getopt.error, msg:
    usage()

  input_stream = sys.stdin

  for opt, arg in opts:
    if opt in ("-f", "--input"):
      input_stream = file(arg, "r")

  if len(args) == 2:
    url = args[0]
    dest = args[1]
  elif len(args) == 1:
    url = args[0]
    dest = "."
  else:
    usage(23)

  if not os.path.exists(dest):
    usage(24, msg="destination directory '%s' does not exist" % dest)

  # Process options
  DownloadPicasaWebAlbum(url, dest)

if __name__ == '__main__':
  main()
